a2s
Strings Timm Sandbox Mar10 Revised

Turning an Array into a String

Problem
=======

Converting array contents to a string, perhaps with some
separator character in between each item.

Solution
========

Synopsis
--------

  a2s(array   [,sep,start,stop])

Print the array from _start_ to _stop_.  
Insert the _sep_ string between each item (defaults to ",").
The default behavior is to print the array from position one till end of array.
If _stop_ is not provided, this function peeks at the _array[0]_ to get the
size of the array.

Code
----

The processing of the first item in the array is different to the rest since
there is no separator to print  before item one.

 function a2s(a,sep,  start, stop,  tmp, out,i) { 
     sep   = sep ? sep : ","
     start = start ? start : 1
     stop  = stop ? stop : a[0]
     for(i=start;i<=stop;i++) 
         out = out (i > start ? sep : "") a[i]     
     return out
 }  

Note the use of optional parameters: if _sep_, _start_, _stop_ are not used
when _a2s_ is called, they are set to default values in the first few
lines of the function.

   function A2s(array,n) {
       array[0] = split("john,has,a,long,mustache",array,",")
       print a2s(array, "|" )      == "john|has|a|long|mustache"
       print a2s(array, "|", 3)    == "a|long|mustache"
       print a2s(array, "|", 2, 4) == "has|a|long"
   }

Discussion
==========

Using _array[0]_ to store the size of an array addresses a bug in gawk, prior to version 3.1.8
in which _length_ crashed in functions if passed an uninitialized array. 

